package com.wzb.mybatisplus.bitaction.electrumaction.one;

import com.wzb.mybatisplus.bitaction.BitcoinPrivateKeyGenerator1;
import org.bitcoinj.core.Address;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.params.MainNetParams;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

public class BlockchainBalanceChecker {

    private static final String BASE_URL = "https://blockchain.info/balance?active=";

    public static String getBalanceForAddresses(List<String> addresses) {
        try {
            // 将地址列表转换为逗号分隔的字符串
            String addressString = String.join("|", addresses);

            URL url = new URL(BASE_URL + addressString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            return response.toString();

        } catch (Exception e) {
            try {
                Thread.sleep(10);
            }catch (Exception e1){}
//            Thread.sleep(1000);
//            e.printStackTrace();
            return null;
        }
    }
    public static String getBalanceForAddresses(String addresses) {
        try {
            // 将地址列表转换为逗号分隔的字符串
            String addressString = addresses;

            URL url = new URL(BASE_URL + addressString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            return response.toString();

        } catch (Exception e) {
            try {
                Thread.sleep(10);
            }catch (Exception e1){}
//            Thread.sleep(1000);
//            e.printStackTrace();
            return null;
        }
    }
    public static String getBalanceForAddressesVPN(List<String> addresses) {
        try {

            String addressString = String.join("|", addresses);
            // 创建HTTP客户端（会自动使用系统VPN设置）
            HttpClient client = HttpClient.newBuilder()
                    .connectTimeout(Duration.ofSeconds(10))
                    .build();

            // 构建请求 - 获取比特币区块数据
            String apiUrl = "https://blockchain.info/balance?active="+addressString;
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(apiUrl))
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
                    .timeout(Duration.ofSeconds(15))
                    .GET()
                    .build();

            // 发送请求并获取响应
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            if(response.statusCode()==200){
                return response.body();
            }else if(response.statusCode()==429){
                return "VPN";
            }else {
                System.out.println(response.statusCode());
                return null;
            }

        } catch (Exception e) {
//            e.printStackTrace();
            return null;
        }
    }


    public static String getBaiduUrl() throws Exception {
        URL url = new URL("https://www.baidu.com/");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        BufferedReader in = new BufferedReader(
                new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        return response.toString();
    }
    // 私钥转公钥
    public static void atob( ){
        String wifPrivateKey = null;

        for(int i=0;i<30;i++){
            BitcoinPrivateKeyGenerator1.BitcoinPrivateKey privateKey = BitcoinPrivateKeyGenerator1.generatePrivateKey();

            if (BitcoinPrivateKeyGenerator1.isValidPrivateKey(privateKey.getPrivateKey())) {  //私钥正确的话
                // 私钥转公钥
                wifPrivateKey = privateKey.getWIFCompressed();

                KeyPair wifKeyPair = null;
                try {
                    wifKeyPair = BitcoinKeyConverter.generateFromWIF(wifPrivateKey);
                } catch (Exception e) {

                }
//                String address = wifKeyPair.getLegacyAddress(); // 比特币创始区块地址公钥地址

                String address = wifKeyPair.getLegacyAddress();
                String gongyao = wifKeyPair.getPublicKeyUncompressed();
                System.out.println("私钥:"+privateKey.getPrivateKey() +" 长度    "+privateKey.getPrivateKey().toString().length()
                        +"    私钥压缩："+wifPrivateKey +"   长度："+ wifPrivateKey.length()+"          公钥："+address +"     长度："+address.length()
                        +"    公钥未压缩"+gongyao +"         长度："+gongyao.length());
            }

        }



    }
    public static boolean isValidBitcoinAddress(String address) {
        try {
            NetworkParameters params = MainNetParams.get();
            Address.fromString(params, address);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    public static void main(String[] args) {
        List<String> addresses = new ArrayList<>();
        String wifPrivateKey = null;
        atob();

        //G = (
        //  x坐标: 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798,
        //  y坐标: 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8
        //)
        //https://blockchain.info/balance?active=1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa|3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy|bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh|1BitcoinEaterAddressDontSendf59kuE|34xp4vRoCGJym3xR7yCVPFHoCNxv4Twseo|bc1qgdjqv0av3q56jvd82tkdjpy7gdp9ut8tlqmgrpmv24sq90ecnvqqjwvw97|1CounterpartyXXXXXXXXXXXXXXXUWLpVr|3E8ociqZa9mZUSwGdSmAEMAoAxBK3FNDcd|bc1q9w4h6q3fqg2vfm7e4k6vjvz3z5vjv8z5vjv8z5|1FLAMEN6FbS91xRYXd6pfgSiHTgWiTkX3f
        // L228ASPc2St5VsmWZ58SwteV5txZv7kGN4wYHo6JZFEYTMVPLaRx
        //148oAWFYGGziasjbtQaZAmwARD17ENqSNq   03569a42f475dedc502c1d2933dae8dd863db9f3dfa9d806de95aa2bb4c5fa3aa5
        //KzvCZM6tbsyfdGTHyufpN6u8pmZwY1em2DixiCpV3axVy4ZU6c1a
        //地址：1CFmN4U5GkN5pQaKBzY5VQEGFxq79tcL2c  公钥：03e7330fe0cb8df89064031b59c70c91a11d308e2e1fd489630b317af007327ee1
        System.out.println("L228ASPc2St5VsmWZ58SwteV5txZv7kGN4wYHo6JZFEYTMVPLaRx".length());
        System.out.println("148oAWFYGGziasjbtQaZAmwARD17ENqSNq".length());
        System.out.println("03569a42f475dedc502c1d2933dae8dd863db9f3dfa9d806de95aa2bb4c5fa3aa5".length());
        System.out.println("KzvCZM6tbsyfdGTHyufpN6u8pmZwY1em2DixiCpV3axVy4ZU6c1a".length());
        System.out.println("1CFmN4U5GkN5pQaKBzY5VQEGFxq79tcL2c".length());
        System.out.println("03e7330fe0cb8df89064031b59c70c91a11d308e2e1fd489630b317af007327ee1".length());
        System.out.println("54162093229368564568710020488845731417819567229398929116959429577753052224008".length());
        Set<String> addressesSys = new HashSet<>();
        addressesSys.add("1234");
        addressesSys.add("2345");
        System.out.println(addressesSys);

        for (int i = 0; i < 300; i++) {
            BitcoinPrivateKeyGenerator1.BitcoinPrivateKey privateKey = BitcoinPrivateKeyGenerator1.generatePrivateKey();
            if (BitcoinPrivateKeyGenerator1.isValidPrivateKey(privateKey.getPrivateKey())) {  //私钥正确的话
                // 私钥转公钥
                wifPrivateKey = privateKey.getWIFCompressed();

            }
//            wifPrivateKey = "L228ASPc2St5VsmWZ58SwteV5txZv7kGN4wYHo6JZFEYTMVPLaRx";
            KeyPair wifKeyPair = null;
            try {
                wifKeyPair = BitcoinKeyConverter.generateFromWIF(wifPrivateKey);
            } catch (Exception e) {

            }
            System.out.println("私钥信息："+privateKey);
            String address = wifKeyPair.getLegacyAddress(); // 比特币创始区块地址公钥地址
            addresses.add(address);
            System.out.println("公钥信息："+wifKeyPair);
        }
        String result = getBalanceForAddresses(addresses);
        JSONObject jsonResponse = new JSONObject(result);
        for (String address : addresses) {
            JSONObject addressInfo = jsonResponse.getJSONObject(address);
//            System.out.println(addressInfo);

            Long maney = addressInfo.getLong("final_balance");
            long total_received = addressInfo.getLong("total_received");
            long jiaoyiliang = addressInfo.getLong("n_tx");
            if (maney > 0.0 || jiaoyiliang > 0.0 || total_received > 0.0) {

                System.out.println(address + ":    " + addressInfo);

            }

        }


        System.out.println("查询结果: " + result);


        }




//            addresses.add("1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa");
//        addresses.add("1BitcoinEaterAddressDontSendf59kuE");
//        addresses.add("1CounterpartyXXXXXXXXXXXXXXXUWLpVr");


}
//svn list https://14.18.232.142:8433/svn/IMSV6/source/2025/达锂 --trust-server-cert --non-interactive --username cooperate_fenglingyoumeng --password fenglym@000
//svn list https://14.18.232.142:8433/svn/IMSV6/source/2025/达锂 --trust-server-cert --non-interactive
//svn checkout --trust-server-cert https://14.18.232.142:8433/svn/IMSV6/source/2025/达锂
//svn list https://14.18.232.142:8433/svn/IMSV6/source/2025/达锂 --trust-server-cert --non-interactive

//svn --non-interactive --trust-server-cert-failures=unknown-ca checkout https://14.18.232.142:8433/svn/IMSV6/source/2025/达锂

//svn --username cooperate_fenglingyoumeng --password "fenglym@000" --non-interactive --trust-server-cert-failures=unknown-ca,cn-mismatch,expired,not-yet-valid,other checkout "https://14.18.232.142:8433/svn/IMSV6/source/2025/达锂"